package com.usian.admin.service.impl

import com.alibaba.fastjson.JSONArray
import com.alibaba.fastjson.JSONObject
import com.usian.admin.feign.ArticleFeign
import com.usian.admin.feign.WemediaFeignClient
import com.usian.admin.mapper.AdChannelMapper
import com.usian.admin.mapper.AdSensitiveMapper
import com.usian.admin.service.WemediaNewsAutoScanService
import com.usian.common.aliyun.GreenImageScan
import com.usian.common.aliyun.GreenTextScan
import com.usian.common.fastdfs.FastDFSClient
import com.usian.model.admin.pojos.AdSensitive
import com.usian.model.article.pojos.ApArticle
import com.usian.model.article.pojos.ApArticleConfig
import com.usian.model.article.pojos.ApArticleContent
import com.usian.model.base.BaseServiceImpl
import com.usian.model.common.dtos.ResponseResult
import com.usian.model.common.enums.AppHttpCodeEnum
import com.usian.model.media.pojos.WmNews
import com.usian.utils.common.SensitiveWordUtil
import io.seata.spring.annotation.GlobalTransactional
import org.elasticsearch.action.index.IndexRequest
import org.elasticsearch.client.RequestOptions
import org.elasticsearch.client.RestHighLevelClient
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Value
import org.springframework.stereotype.Service
import java.io.IOException
import java.util.*


@Service
open class WemediaNewsAutoScanServiceImpl :BaseServiceImpl<AdSensitiveMapper, AdSensitive>(), WemediaNewsAutoScanService {


    @Value("\${file.url}")
    private lateinit var fileUrl:String

    @Autowired
    private lateinit var newsClient: WemediaFeignClient

    @Autowired
    private lateinit var greenImageScan: GreenImageScan

    @Autowired
    private lateinit var greenTextScan: GreenTextScan

    @Autowired
    private lateinit var fastDFSClient: FastDFSClient

    @Autowired
    private lateinit var articleFeign: ArticleFeign

    @Autowired
    private lateinit var adChannelMapper: AdChannelMapper;

    @Autowired
    private lateinit var restHighLevelClient: RestHighLevelClient;



    @GlobalTransactional
    override fun autoScanByMediaNewsId(id: Int?): ResponseResult<*>? {
        if (id == null)return errorParam
        val wmNews = newsClient.findById(id) ?: return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST)

        if (wmNews.status.equals(WmNews.Status.ADMIN_SUCCESS.code) || wmNews.status.equals(WmNews.Status.SUCCESS.code)){
            if (wmNews.publishTime.time <= Date().time){
                wmNews.status = WmNews.Status.PUBLISHED.code
                wmNews.reason="审核通过"
                newsClient.updateWmNews(wmNews)
                return success
            }
        }
        var content = wmNews.content
        var jsonArray: JSONArray = JSONArray.parseArray(content)
        var images = ArrayList<String>()
        var conts =StringBuilder()
        jsonArray.forEach(){
            val obj = JSONObject.parseObject(it.toString())
            if (obj["type"] != "text"){
                images.add(obj["value"].toString().replace(fileUrl,""))
            }else{
                conts.append(obj["value"].toString())
            }
        }

        if (wmNews.status == WmNews.Status.SUBMIT.code) {
            //文章内容审核
            val textScan = greenTextScan.greeTextScan(conts.toString())
            if (textScan["suggestion"] == "block") {
                wmNews.status = WmNews.Status.FAIL.code
                wmNews.reason="阿里云文章审核未通过"
                newsClient.updateWmNews(wmNews)
                return ResponseResult.errorResult("文章审核失败")
            }else if (textScan["suggestion"] == "review"){
                wmNews.status = WmNews.Status.ADMIN_AUTH.code
                wmNews.reason="需要人工审核"
                newsClient.updateWmNews(wmNews)
                return ResponseResult.errorResult("文章审核失败")
            }

            //图片审核
            var list = mutableListOf<ByteArray>()
            images.forEach {
                val index = it.indexOf("/")
                var group = it.substring(0, index)
                var path = (it+"1").substring(index+1, it.length)
                var bytes = fastDFSClient.download(group, path)
                list.add(bytes)
            }

            val imageScan = greenImageScan.imageScan(list)
            if (textScan["suggestion"] == "block") {
                wmNews.status = WmNews.Status.FAIL.code
                wmNews.reason="阿里云图片审核未通过"
                newsClient.updateWmNews(wmNews)
                return ResponseResult.errorResult("图片审核失败")
            }else if (textScan["suggestion"] == "review"){
                wmNews.status = WmNews.Status.ADMIN_AUTH.code
                wmNews.reason="需要人工审核"
                newsClient.updateWmNews(wmNews)
                return ResponseResult.errorResult("需要人工审核")
            }

             var ses=baseMapper.findAllSensitive()
            //敏感字审核
            SensitiveWordUtil.initMap(ses)
            if (SensitiveWordUtil.matchWords(content).isNotEmpty()){
                wmNews.status = WmNews.Status.FAIL.code
                wmNews.reason = "敏感字审核失败"
                newsClient.updateWmNews(wmNews)
                return ResponseResult.errorResult("敏感字审核失败")
            }

            return saveData(wmNews)
            /*      var a=1/0*/

        }
        return null
    }

    private fun saveData(wmNews: WmNews): ResponseResult<*>? {
        //根据新闻id查询自媒体人信息
        val wmUser = newsClient.findWmUserById(wmNews.userId)
            ?: return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST)
        //根据用户id查询作者信息
        var author = articleFeign.findByUserId(wmUser.apUserId)
            ?: return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST)
        //根据频道id查询频道信息
        var channel = adChannelMapper.selectById(wmNews.channelId)
            ?: return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST)
        var apArticle = ApArticle()
        apArticle.apply {
            title = wmNews.title
            authorId = author.id
            authorName = author.name
            channelId = channel.id
            channelName = channel.name
            layout = wmNews.type
            flag = 0
            this.images = wmNews.images
            labels = null
            likes = 0
            collection = 0
            comment = 0
            views = 0
            provinceId = 1
            cityId = 1
            countyId = 1
            createdTime = wmNews.createdTime
            publishTime = wmNews.publishTime
            syncStatus = true
            origin = true
        }

        val article = articleFeign.saveArticle(apArticle)
        var apArticleConfig = ApArticleConfig()
        apArticleConfig.apply {
            articleId = article.id
            isComment = 1
            isForward = 1
            isDown = 0
            isDelete = 0
        }
        articleFeign.saveArticleConfig(apArticleConfig)
        var apArticleContent = ApArticleContent()
        apArticleContent.apply {
            articleId = article.id
            this.content = wmNews.content
        }
        articleFeign.saveArticleContent(apArticleContent)
        if (wmNews.publishTime>Date()){
            wmNews.status = WmNews.Status.SUCCESS.code
        }else{
            wmNews.status = WmNews.Status.PUBLISHED.code
        }
        wmNews.reason="审核通过"
        wmNews.articleId=article.id
        newsClient.updateWmNews(wmNews)
        //es索引创建
        val map: MutableMap<String?, Any?> = mutableMapOf<String?, Any?>()
        map["id"] = apArticle.id.toString()
        map["publishTime"] = apArticle.publishTime
        map["layout"] = apArticle.layout
        map["images"] = apArticle.images
        map["authorId"] = apArticle.authorId
        map["title"] = apArticle.title
        map["content"] = wmNews.content

        //创建文档添加到索引库中
        val indexRequest: IndexRequest = IndexRequest("app_info_article").id(apArticle.id.toString()).source(map)
        try {
            restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT)
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return success
    }

}
